# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

import os, sys
import re
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))
sys.path.insert(0, parent_dir_path)
from flask import Blueprint
from flask import request
import json
import time
import datetime
import threading
from payapi import paycommon
import utils.common.log as log
from utils.common.func import time_data
import utils.pgsql.pgpay as pgpay
import utils.pgsql.pgpayflow as pgpayflow
import utils.pgsql.pgtechpay as pgtechpay
import utils.pgsql.pgtechpayflow as pgtechpayflow
import utils.message.response as response
import utils.message.response as response
import utils.common.httpclient as httpclient
import utils.pgsql.pgadmin as pgadmin
import redis
from utils.wraps import token, urlcost

# Obtain fund flow information

paymanage_module = Blueprint("paymanage", __name__, url_prefix="/payapi/isv_app/order")

def getYesterday():
    """
     获取前一天日期 2022-03-29
    :return: 
    """
    yesterday = datetime.date.today() + datetime.timedelta(-1)
    return yesterday


@paymanage_module.route("/paymentsave", methods=["POST"])
def paymentsave():
    Info = json.loads(request.data)
    obj = pgpay.PgPay()
    ret = obj.addpay(Info)  # 插入 tbl_pay 库
    if ret:
        return response.make_response_success_no_data()
    else:
        return response.make_response_1000()


def deviation_date(date, offsets):
    start_date = datetime.datetime.strptime(date, "%Y-%m-%d")
    now_date = datetime.timedelta(days=offsets)
    a = start_date + now_date
    return a.strftime("%Y-%m-%d")


@paymanage_module.route("/chanorderList", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def chanorderList():
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    Info = json.loads(request.data)
    end_date = Info[1][1]
    begin_date = Info[1][0]
    obj = pgpay.PgPay()
    ret = obj.chanpay(
        Info[0],#由渠道ID改成项目名了 ps: "亚龙湾_水滑道漂流"
        datetime.datetime.strptime(begin_date, "%Y-%m-%d"),
        datetime.datetime.strptime(deviation_date(end_date, +1), "%Y-%m-%d"),
        caseId=Info[2]
    )
    log.logging.info("ret:{}".format(ret))

    return response.make_response_success(ret)

def deviation_date(date, offsets):
    start_date = datetime.datetime.strptime(date, "%Y-%m-%d")
    now_date = datetime.timedelta(days=offsets)
    a = start_date + now_date
    return a.strftime("%Y-%m-%d")


@paymanage_module.route("/orderDetail", methods=["POST"])
def orderDetail():
    """
    {
    "fllow_id": "XXXXXX"
    }
    :return: [{}]
    """
    dic = json.loads(request.data)
    orderList = []
    if "fllow_id" in dic and dic['fllow_id']: # fllow_id 流水ID 或者 use_id
        obj = pgtechpayflow.Pgtechpayflow()
        orderList = obj.single(dic['fllow_id'])
        if orderList:
            orderList[0]['openId'] = orderList[0]['caseName']
    return response.make_response_success(orderList)


@paymanage_module.route("/orderList", methods=["POST"])
def orderList():
    """input param:
    {
        "pageNo": 1 ,
        "pageSize": 10 ,
        "channelInfo":"xxx",
        "caseId":"0",
        "operatorId":"1",
        "startTime":16xxxx,
        "endTime":16xxxxx
    }
    """
    cache = redis.Redis(host='10.206.0.115', port=6379, db=10, password='SKadmin123_456')
    t1 = cache.get(request.headers["Authorization"]) # b'929'
    limit = ""
    if t1:
        admin_id = int(t1)
        obj = pgadmin.PgAdmin()
        user_dic = obj.get(admin_id)
        limit = user_dic['playground_limit']
    dic = json.loads(request.data)
    channelInfo = ""
    startTime = ""
    endTime = ""
    if "startTime" in dic and "endTime" in dic:
        startTime = time_data(dic["startTime"])
        endTime =  datetime.datetime.strptime(deviation_date(time_data(dic["endTime"]), +1), "%Y-%m-%d")
    else:
        startTime = "1976-01-01"
        endTime_str = time.strftime("%Y-%m-%d", time.localtime())
        endTime = datetime.datetime.strptime(deviation_date(endTime_str, +1), "%Y-%m-%d")
    if "adminId" not in dic :
        dic["adminId"] =  "-1"

    if "channelInfo" in dic :
        if dic["channelInfo"] !="" :
            channelInfo = "%" + dic["channelInfo"] + "%"

    if "operatorId" in dic:
        operatorId = dic["operatorId"]
    else:
        operatorId = "1"
    if operatorId == "1": 
        obj = pgtechpayflow.Pgtechpayflow()
        
    orderList = ""
    if "caseId" in dic:
        orderList = obj.PageCase(dic["caseId"],channelInfo,dic["pageNo"],dic["pageSize"],startTime,endTime,limit=limit)
    else:
        if dic["adminId"] =="1":
            orderList = obj.PageAll(channelInfo, dic["pageNo"], dic["pageSize"], startTime, endTime)
    log.logging.info("orderList:{}".format(orderList))
    if orderList == "":
        return response.make_response_1505()
    return response.make_response_success(orderList)


@paymanage_module.route("/paydevide", methods=["POST"])
def paydevide():
    pay = pgpay.PgPay()
    payflow = pgpayflow.Pgpayflow()
    paycommon.devidedinto_pay(pay, payflow, -1)
    obj_payflow = pgpayflow.Pgpayflow()
    today_pay = obj_payflow.GetAllTodayList(datetime.date.today())
    return response.make_response_success(today_pay)


def _time_devidedinto_task():

    while True:
        if datetime.datetime.now().hour == 2:
            time.sleep(4)
            pay = pgpay.PgPay()
            payflow = pgpayflow.Pgpayflow()
            paycommon.devidedinto_pay(pay, payflow, -1)
            time.sleep(4000)
        else:
            time.sleep(3500)


t2 = threading.Thread(target=_time_devidedinto_task, daemon=True)
t2.start()


if __name__ == "__main__":

    pay = pgpay.PgPay()
    payflow = pgpayflow.Pgpayflow()
    paycommon.devidedinto_pay(pay, payflow, -1)
    print("tech test : #######################################")
